<!-- 项目调整 -->
<template>
	<view>
		<form>
			<view class="cu-form-group">
			    <view class="title">提问</view>
			    <textarea class="textarea-content" 
			              v-model="projectItem.projectName" 
			              placeholder="请输入详细描述（200字以内）"
			              maxlength="200"
			              auto-height />
						  <input
						      type="text" 
						      v-model="projectItem.uid" 
						      hidden 
						    />
			  </view>
			<view class="cu-form-group">
				<view class="title">回复</view>
 <textarea class="textarea-content" 
			              v-model="projectItem.projectType" 
			              placeholder="请输入详细描述（200字以内）"
			              maxlength="200"
			              auto-height />			
				
			</view>			
			
		</form>
		<view class="flex">
			<view class="flex-sub margin-sm">
				<button class="cu-btn block shadow bg-white margin-tb-sm lg" @tap="cancelClick">取消</button>
			</view>
			<view class="flex-sub margin-sm">
				<button class="cu-btn block shadow bg-blue margin-tb-sm lg" @tap="saveClick">保存</button>
			</view>
		</view>
	</view>
</template>

<script>
	import { mapGetters } from 'vuex'
	import tuiDatetime from "@/components/tui/tui-datetime.vue"
	var graceChecker = require("../../utils/graceChecker.js")
	export default {
		components: {
			tuiDatetime
		},
		computed: {
			...mapGetters(['themeBgColor', 'darkMode']),
		},
		async mounted() {
			console.log('从Vuex获取的数据:', this.userData)
			console.log("映射的getters:", this.$store.getters);
			console.log("映射的getters getUserData", this.$store.getters.getUserData);			
		},
		onReady() {
			uni.setNavigationBarTitle({
			    title: this.$t('ProjectAdjust')
			})
			// navBar-bg-color
			uni.setNavigationBarColor({
			    frontColor: '#ffffff',
			    backgroundColor: this.themeBgColor,
			    animation: {
			        duration: 400,
			        timingFunc: 'easeIn'
			    }
			})
		},
		async onLoad(options) {
		    try {
		        // 先检查登录状态
		        await this.checkAuth();
		        
		        // 获取用户数据（确保在checkAuth之后）
		        const uid = this.$store.getters.getUserData?.uid || 'default_uid';
		        console.log(this.userData); // 触发 userData() 计算
				console.log("project -add onLoad() this.uid:",this.uid); // 触发 userData() 计算,这个this.uid是没值的
				console.log("project -add  onLoad() uid:",uid); // 触发 userData() 计算
		        
		        // 处理项目数据
		        try {
		            this.projectItem = JSON.parse(options.data || '{}');
		            //console.dir(this.projectItem);
					console.log("after try json parse",this.projectItem);
		            this.areaIndex = this.areaMap[this.projectItem.area];
		            this.addrIndex = this.addrMap[this.projectItem.addr];
					this.projectName = this.projectItem.projectName;
					this.projectType = this.projectItem.projectType;
		            this.applyTime = this.projectItem.applyTime;
		            this.createTime = this.projectItem.createTime;
					 this.uid = uid;
					 console.log('try block',this.projectItem);
		        } catch (e) {
					console.log("project data init fail, set the default");
		            this.projectItem = {
		                applyTime: '',
						projectName: '',
		                projectType: '',
		                area: '',
		                createTime: '',
		                addr: '',
						uid:uid
		            };
					 console.log('catch block',this.projectItem);
		        }
		        
		        // 初始化操作（如果有需要）
		        // this.$refs.auditProjectRef?.queryBylist();
		    } catch (error) {
		        console.error('页面加载出错:', error);
		        // 可以根据错误类型进行不同的处理
		        uni.showToast({
		            title: '加载失败',
		            icon: 'none'
		        });
		        // 如果需要跳转到登录页
		        // uni.redirectTo({ url: '/pages/login/login' });
		    }
		},
		
		
		
		data() {
			return {
				startYear: new Date().getFullYear(),
				endYear: 2050,
				cancelColor: "#888",
				color: "#5677fc",
				setDateTime: '',
				placeholder: '请选择日期时间',

				projectItem: {
					applyTime: '',
					projectName: '',
					projectType: '',					
					area: '',
					createTime: '',
					addr: '',
					uid: uid
				},
				areaIndex: -1,
				addrIndex: -1,
				areaList: [
					'省内',
					'省外'
				],
				addrList: [
					'四川',
					'广东',
					'安徽'
				],
				areaMap: {
					'省内': 0,
					'省外': 1
				},
				addrMap: {
					'四川': 0,
					'广东': 1,
					'安徽': 2
				},
				formRule: [{
						name: "projectName",
						checkType: "notnull",
						checkRule: "",
						errorMsg: "请输入知识库疑问"
					},
					{
						name: "projectType",
						checkType: "notnull",
						checkRule: "",
						errorMsg: "请输入知识库回复"
					}					
				]
			}
		},
		methods: {
			async checkAuth() {
					const uid = this.$store.getters.getUserData?.uid || 'default_uid'
					console.log('checkauth uid', uid);			
						if (uid == "default_uid") {
							console.log('未登录或uid不存在，跳转登录')					
							/* uni.redirectTo({
							  url: '/pages/login/login?redirect=' + 
							       encodeURIComponent(getCurrentPages().pop()?.route || '/pages/index/index')
							}) */
							this.$router.push('/pages/login/login'); // 跳转到登录页
							return false
						} else {
							console.log('已登录且uid存在，继续执行')
							 this.$nextTick().then(() => {  // ✅ 用 .then 代替 await
							    if (this.$refs.auditProjectRef?.queryBylist) {
							      this.$refs.auditProjectRef.queryBylist();
							    }
							  });							
							return true
							}
				 
			},
			// 时间日期选择start
			showApplyTime() {
				this.$refs.applyDateTimeRef.show()
			},
			showCreateTime() {
				this.$refs.createDateTimeRef.show()
			},
			getApplyTime(e) {
				this.projectItem.applyTime = e.result
			},
			getCreateTime(e) {
				this.projectItem.createTime = e.result
			},
			// 时间日期选择end

			areaPickerChange(e) {
				this.areaIndex = e.detail.value
				this.projectItem.area = this.areaList[this.areaIndex]
			},
			addrPickerChange(e) {
				this.addrIndex = e.detail.value
				this.projectItem.addr = this.addrList[this.addrIndex]
			},
			cancelClick() {
				uni.navigateBack({
					delta: 1
				})
			},
			// 跳转上一页并刷新
			updateQuery() {
				// 更新数据
				let pages = getCurrentPages()
				// let currPage = pages[pages.length - 1]; //当前页面
				let prevPage = pages[pages.length - 2] //上一个页面
				//prevPage.isDoRefresh = true
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}, 1000)
			},
			async saveClick() {
				console.log('project-add saveClick',this.projectItem);
				const res = await this.$minApi.updateAuditProject(this.projectItem)
				//const res = await this.$minApi.addAuditProject(this.projectItem)
				if (!this.projectItem && !this.projectItem.id) {
					uni.showToast({
						title: '请选择一个待审核预约！',
						icon: 'none'
					})
					return
				}
				var checkRes = graceChecker.check(this.projectItem, this.formRule);
				if (checkRes) {
					let tmp = { ...this.projectItem
					}
					// 时间字符串转换为时间
					tmp.applyTime = new Date(tmp.applyTime)
					tmp.createTime = new Date(tmp.createTime)
					uni.showLoading({
						title: '正在提交数据...'
					})
					/**
					 * todo: api请求
					 */
					setTimeout(() => {
						uni.hideLoading()
						uni.showToast({
							title: '保存成功！',
							icon: 'success'
						})
						this.updateQuery() //这个最后是跳转首页，调试时先屏蔽
					}, 3000)
				} else {
					uni.showToast({
						title: graceChecker.error,
						icon: 'none'
					})
				}
			}
		}
	}
</script>

<style>
	.form-container {
	  padding: 20rpx 30rpx;
	  box-sizing: border-box;
	  height: calc(100vh - 100rpx);
	}
	
	.cu-form-group {
	  margin-bottom: 30rpx;
	  align-items: flex-start;
	}
	
	.title {
	  width: 160rpx;
	  font-size: 30rpx;
	  color: #333;
	  padding-top: 10rpx;
	}
	
	.input-content {
	  flex: 1;
	  padding: 20rpx 0;
	  font-size: 28rpx;
	  min-height: 60rpx;
	  border-bottom: 1rpx solid #eee;
	}
	
	.textarea-content {
	  flex: 1;
	  padding: 20rpx;
	  font-size: 28rpx;
	  min-height: 120rpx;
	  border: 1rpx solid #eee;
	  border-radius: 8rpx;
	  background-color: #f9f9f9;
	}
	
	.footer-fixed {
	  position: fixed;
	  bottom: 0;
	  left: 0;
	  right: 0;
	  padding: 20rpx;
	  background: #fff;
	  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
	}
	
	.submit-btn {
	  background-color: #007aff;
	  color: white;
	  height: 80rpx;
	  line-height: 80rpx;
	  border-radius: 40rpx;
	  font-size: 32rpx;
	}
	
	
	.placeholder {
		color: #8c8c8c;
		line-height: 84rpx;
		font-size: 31rpx;
		-o-text-overflow: ellipsis;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
		width: 100%;
		text-align: right;
	}

	.my-uni-input {
		line-height: 84rpx;
		font-size: 31rpx;
		-o-text-overflow: ellipsis;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
		width: 100%;
		text-align: right;
	}

	.cu-form-group .time-content {
		-webkit-box-flex: 1;
		-webkit-flex: 1;
		-ms-flex: 1;
		flex: 1;
		padding-right: 33rpx;
		overflow: hidden;
		position: relative;
	}

	.cu-form-group .time-content::after {
		font-family: cuIcon;
		display: block;
		content: "\E6A3";
		position: absolute;
		font-size: 31rpx;
		color: #8799a3;
		line-height: 84rpx;
		width: 50rpx;
		text-align: center;
		top: 0;
		bottom: 0;
		right: -16rpx;
		margin: auto;
	}
</style>
